import http from "wechat-http";

Page({
  data: {
    mobile: "13800000003",
    code: "246810",
    mobileErr: "",
    codeErr: "",
  },

  validate(type, val) {
    return new Promise((resolve, reject) => {
      const patternMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      const patternCode = /^\d{6}$/;
      const pattern = type === "mobile" ? patternMobile : patternCode;
      if (val.trim() === "") {
        reject(type === "mobile" ? "请输入手机号" : "请输入验证码");
      } else {
        if (pattern.test(val)) {
          resolve("");
        } else {
          reject(type === "mobile" ? "手机号格式不正确" : "验证码格式不正确");
        }
      }
    });
  },

  checkMobile() {
    const p = this.validate("mobile", this.data.mobile);
    p.then((res) => {
      this.setData({
        mobileErr: res,
      });
    }).catch((err) => {
      this.setData({
        mobileErr: err,
      });
    });
    return p;
  },

  checkCode() {
    const p = this.validate("code", this.data.code);
    p.then((res) => {
      this.setData({
        codeErr: res,
      });
    }).catch((err) => {
      this.setData({
        codeErr: err,
      });
    });
    return p;
  },

  async submitLogin() {
    try {
      await this.checkMobile();
      await this.checkCode();
      const data = {
        mobile: this.data.mobile,
        code: this.data.code,
      };
      const res = await wx.http.post("/v1_0/authorizations", data);
      console.log("登录信息", res);
      if (res.statusCode === 400) {
        wx.showToast({
          title: res.data.message,
          icon: "error",
          duration: 1500,
        });
      }
      if (res.statusCode === 201) {
        wx.showToast({
          title: "登录成功",
          icon: "success",
          duration: 1500,
        });
        wx.setStorageSync("HMTT-token", res.data.data.token);
        getApp().token = res.data.data.token;
        console.log("仓库token：", getApp().token);
        wx.redirectTo({
          url: "/pages/my/index",
        });
      }
    } catch (error) {
      console.log(error);
    }
  },
});
